package euler.p051_100;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import euler.MainEuler;
import euler.helper.Utils;

public class Euler081 extends MainEuler {

    /*
        In the 5 by 5 matrix below, the minimal path sum from
        the top left to the bottom right, by only moving to the
        right and down, is indicated in bold red and is equal to 2427.


        131 673 234 103 18
        201 96  342 965 150
        630 803 746 422 111
        537 699 497 121 956
        805 732 524 37  331


        Find the minimal path sum, in http://projecteuler.net/project/matrix.txt,
        a 31K text file containing a 80 by 80 matrix, from the top
        left to the bottom right by only moving right and down.

     */
    public String resolve() throws IOException {

        int length = 80;
        int[][] matrix = new int[length][];

        String filePath = Utils.pathToFiles + "matrix.txt";

        BufferedReader br = null;

        try {
            br = new BufferedReader(new FileReader(new File(filePath)));
            String strLine;
            int i = 0;
            while ((strLine = br.readLine()) != null)   {

                String[] split = strLine.split(",");

                int[] row = new int[split.length];

                for (int j = 0; j < row.length; j++) {
                    row[j] = Integer.valueOf(split[j]);
                }

                matrix[i++]=row;
            }
        } finally {
            if (br != null) {
                br.close();
            }
        }



        int[][] minimalMatrix = new int[length][length];

        minimalMatrix[length-1][length-1] = matrix[length-1][length-1];

        for (int i = length - 2; i >= 0; i--) {
            minimalMatrix[i][length-1] = minimalMatrix[i+1][length-1] + matrix[i][length-1];
            minimalMatrix[length-1][i] = minimalMatrix[length-1][i+1] + matrix[length-1][i];
        }

        for (int i = length - 2; i >= 0; i--) {
            for (int j = i; j >= 0; j--) {
                minimalMatrix[i][j] = matrix[i][j] + Math.min(minimalMatrix[i+1][j], minimalMatrix[i][j+1]);
                minimalMatrix[j][i] = matrix[j][i] + Math.min(minimalMatrix[j+1][i], minimalMatrix[j][i+1]);
            }
        }

        return String.valueOf(minimalMatrix[0][0]);
    }

}
